<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class RoleRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules(Request $request)
    {
        switch ($this->method()) {
            case 'POST':
                $rules = [
                    'name' => [Rule::unique('roles')->whereNull('deleted_at')->where('parent_id', '=', request()->input('parent_id')),'required','max:20','min:2'],
                    'parent_id' => 'nullable|exists:roles,id',
                    'is_role' => 'nullable|in:0,1',
                ];
                break;
            case 'PATCH':
                $parent_id = $request->route('role')->parent_id;
                if($parent_id){
                    $rules = [
                        'name' => [Rule::unique('roles')->whereNot('id',$request->route('role')->id)->where('parent_id',$parent_id)->whereNull('deleted_at'),'required','max:20','min:2'],
                    ];
                }else{
                    $rules = [
                        'name' => [Rule::unique('roles')->whereNot('id',$request->route('role')->id)->whereNull('parent_id')->whereNull('deleted_at'),'required','max:20','min:2'],
                    ];
                }
                break;
        }
        return $rules;
    }

    public function attributes()
    {
        return [
            'id' => '层级数据',
        ];
    }
}
